/*
 * @Description: webpack公共配置
 * @Author: chenjiaxin
 * @Date: 2024-10-28 10:03:22
 * @LastEditTime: 2024-12-03 11:29:39
 */
const { rootPath, distDir, sourceDir, staticDir } = require("./app.config");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = () => {
  const isDevelopment = process.env.NODE_ENV !== "production";
  const isProduction = process.env.NODE_ENV === "production";

  const commonStyleLoader = [
    isDevelopment && "style-loader",
    isProduction && MiniCssExtractPlugin.loader,
    "css-loader",
    {
      loader: "postcss-loader",
      options: {
        postcssOptions: {
          plugins: ["postcss-preset-env", "tailwindcss"],
        },
      },
    },
  ];

  return {
    entry: {
      index: rootPath(sourceDir, "index.tsx"),
    },
    output: {
      filename: isDevelopment ? "[name].js" : "[name].[contenthash:8].js", // bundle
      path: rootPath(distDir),
      clean: true,
    },
    resolve: {
      extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
      alias: {
        "@": rootPath(sourceDir),
      },
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: "react18-webpack5-demo",
        filename: "index.html",
        template: rootPath(staticDir, "index.html"),
      }),
      isProduction &&
        new MiniCssExtractPlugin({
          filename: isDevelopment
            ? "style/[name].css"
            : "style/[name].[contenthash:8].css",
        }),
    ],
    module: {
      rules: [
        {
          test: /\.(ts|tsx|js|jsx)$/,
          include: [rootPath(sourceDir)],
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
            options: {
              plugins: [
                isDevelopment && require.resolve("react-refresh/babel"),
              ].filter(Boolean),
            },
          },
        },
        {
          test: /\.html$/,
          use: {
            loader: "html-loader",
          },
        },
        {
          test: /\.css$/,
          exclude: /node_modules/,
          use: commonStyleLoader,
        },
        {
          test: /\.less$/,
          exclude: /node_modules/,
          use: [...commonStyleLoader, "less-loader"],
        },
        {
          test: /\.(jp(e)g|png|gif)$/,
          include: [rootPath(sourceDir)],
          type: "asset",
          parser: {
            dataUrlCondition: {
              maxSize: 8 * 1024,
            },
          },
          generator: {
            filename: isDevelopment
              ? "img/[name].[ext]"
              : "img/[name].[contenthash:8].[ext]",
          },
        },
      ],
    },
  };
};
